# -*- coding: utf-8 -*-

import threading, requests
import queue, time
from WSCounter import WSCounter

class HostsValidator:
	def validate(self, names, ip):
		print("Start host validate in " + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
		
		result = []
		
		namesQueue = queue.Queue()
		for name in names:
			namesQueue.put(name)
		
		vCounter = WSCounter(25, 250)
		for i in range(5):
			worker = HostsValidatorThread(namesQueue, ip, result, vCounter)
			worker.daemon = True
			worker.start()
		namesQueue.join()
		
		print("\nHosts validation ended in " + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
		
		return result
#TODO валидация по рег. выр или простой строке
class HostsValidatorThread(threading.Thread):
	def __init__(self, namesQueue, ip, result, counter):
		super().__init__()
		self.result = result
		self.namesQueue = namesQueue
		self.ip = ip
		self.counter = counter
	
	def run(self):
		
		check = requests.get("http://" + self.ip, headers={'Host': 'notvalidandnotexistshost.me.ws'})
		
		while True:
			try:
				name = self.namesQueue.get()
				
				self.counter.up()
					
				try:
					content = requests.get("http://" + self.ip, headers={'Host': name})
					if content.text != check.text:
						self.result.append(name)	
				except queue.Empty:
					break
			finally:
				self.namesQueue.task_done()		